// utils/request.js
import config from '@/config'

// 创建请求实例
const request = (options) => {
  return new Promise((resolve, reject) => {
    const token = uni.getStorageSync('token')
    const url = config.baseURL + options.url
    
    console.log('Request:', {
      url,
      method: options.method || 'GET',
      data: options.data
    })
    
    uni.request({
      url,
      method: options.method || 'GET',
      data: options.data,
      header: {
        'Content-Type': 'application/json',
        'Authorization': token ? `Bearer ${token}` : '',
        ...options.header
      },
      success: (res) => {
        console.log('Response:', res)
        if (res.statusCode === 200) {
          resolve(res.data)
        } else if (res.statusCode === 401) {
          // token过期，清除用户信息并跳转到登录页
          uni.removeStorageSync('token')
          uni.removeStorageSync('userInfo')
          reject(new Error('登录已过期，请重新登录'))
        } else {
          reject(new Error(res.data.message || '请求失败'))
        }
      },
      fail: (err) => {
        console.error('Request Error:', err)
        reject(new Error(err.errMsg || '网络请求失败'))
      }
    })
  })
}

export default request